package com.zhiyou100.dao;

import com.zhiyou100.entity.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImp   implements  UserDao{
    public void  changeUstatus(int uid,int ustatus){
          Query query=getSession().createQuery("update com.zhiyou100.entity.User u set u.ustatus =:us where u.uid=:id");
          query.setInteger("us",ustatus);
          query.setInteger("id",uid);
          query.executeUpdate();
    }
    @Autowired
    private SessionFactory  factory;
    private Session getSession(){
        return factory.openSession();
    }
    @Override
    public User getOneByUname(String uname) {
        return (User) getSession().createCriteria(User.class).add(Restrictions.eq("uname",uname)).uniqueResult();
    }

    @Override
    public void addOne(User o) {
        getSession().save(o);
    }

    @Override
    public void deleteOne(Integer uid) {
        User u=getOne(uid);
        if(u==null){return;}
        getSession().delete(u);
    }

    @Override
    public void updateOne(User o) {
        User u=getOne(o.getUid());
        if(u==null){return;}
        getSession().update(o);
    }

    @Override
    public List<User> getAll() {
        return getSession().createQuery("from com.zhiyou100.entity.User").list();
    }

    @Override
    public User getOne(Integer uid) {
        return getSession().get(User.class,uid);
    }

}
